import React, { useState, useEffect, useRef } from "react";
import { Form, Input, Button, Select, DatePicker, InputNumber, message } from "antd";
import { SearchOutlined, SwapRightOutlined } from "@ant-design/icons";
import AntdWrapper from "@/components/AntdWrapper";
import { customTrimFunc } from "@/utils/utils.jsx";
import IconFont from "@/components/IconFont";
import BatchSuffixInput from "@/views/components/BatchSuffixInput";
import styles from "./index.module.less";
import QuickSearchModal from "./QuickSearchModal";
import QueryButton from "./QueryButton.jsx";
import { getQuickSearchList, delQuickSearchOp } from "../../../../services";

const { Option } = Select;
const { RangePicker } = DatePicker;

//不能价格下拉对应最小的字段
const minPriceMap = {
	1: "minGoodsPrice",
	2: "minGoodsMarketPrice",
	3: "minGoodsSnackPrice"
};

//不能价格下拉对应最大的字段
const maxPriceMap = {
	1: "mixGoodsPrice",
	2: "maxGoodsMarketPrice",
	3: "maxGoodsSnackPrice"
};

const SearchForm = ({ query, queryChangeFunc, handleSetQuery }) => {
	const [form] = Form.useForm();
	const [priceType, setPriceType] = useState(1);
	const [items, setItems] = useState([]); //快捷搜索配置
	const [visible, setVisible] = useState(false);
	const [quickSearchId, setQuickSearchId] = useState("");

	useEffect(() => {
		form.resetFields();
	}, [query]);

	useEffect(() => {
		handelGetConfigList();
	}, []);

	const handelGetConfigList = async () => {
		const { data, success } = await getQuickSearchList({ page: "no-match-detail" });
		if (success) {
			setItems(data);
		}
	};

	//点击重置
	const onReset = () => {
		queryChangeFunc({}, true);
	};

	//检测表单是否有值
	const checkHasValue = obj => {
		Object.keys(obj).some(item => {
			const currentValue = obj[item];
			if (typeof currentValue == "undefined") {
				delete obj[item];
			} else if (Array.isArray(currentValue) && !currentValue?.length) {
				delete obj[item];
			}
		});
		return Boolean(Object.keys(obj)?.length);
	};

	//快捷查询保存
	const handleSaveQuickSearch = () => {
		if (items?.length >= 5) {
			return message.warn("搜索条件保存5个配置，请删除后再尝试");
		}
		const value = form.getFieldsValue();
		if (checkHasValue(value)) {
			setVisible(true);
		} else {
			message.info("请先进行检索");
		}
	};

	//s删除快捷查询
	const handelDelete = async configId => {
		const { data, success } = await delQuickSearchOp({ configId });
		if (success) {
			handelGetConfigList();
		}
	};

	//快捷查询
	const QuickSearchModalProps = {
		items,
		searchForm: form.getFieldsValue(),
		page: "no-match-detail",
		handleOk() {
			setVisible(false);
			handelGetConfigList();
		},
		handleCancel() {
			setVisible(false);
		}
	};

	//快捷搜索展示
	const queryButtonProps = {
		items,
		form,
		quickSearchId,
		onClear: handelDelete,
		onClick(id) {
			setQuickSearchId(id);
			queryChangeFunc(customTrimFunc(form.getFieldsValue(), false));
		}
	};

	return (
		<Form
			form={form}
			// className="new-search-form-style"
			className={styles.formContent}
			onFinish={() => queryChangeFunc(customTrimFunc(form.getFieldsValue(), false))}
			name="express-warning-search-form"
			initialValues={{ ...query }}
		>
			{visible && <QuickSearchModal {...QuickSearchModalProps} />}
			<div className={styles.AntdWrapper}>
				<Form.Item label="" name="goodsName">
					<BatchSuffixInput
						autoMultiLine
						allowClear
						clearable
						maxItem={500}
						zIndex={1200}
						placeholder="多个商品名称，以逗号隔开"
						message="多个商品名称， 每行输入1个内容，最多500个"
					/>
				</Form.Item>
			</div>

			<div className={styles.AntdWrapper}>
				<Form.Item label="" name="goodsCode">
					<BatchSuffixInput
						autoMultiLine
						allowClear
						clearable
						maxItem={500}
						zIndex={1200}
						placeholder="多个商品编码，以逗号隔开"
						message="多个商品编码， 每行输入1个内容，最多500个"
					/>
				</Form.Item>
			</div>

			<div className={styles.AntdWrapper}>
				<Form.Item label="" name="goodsSpec" colon={false}>
					<Input allowClear placeholder="颜色规格" />
				</Form.Item>
			</div>

			<div className={styles.AntdWrapper}>
				<Form.Item label="" name="goodsSpuCode" colon={false}>
					<BatchSuffixInput
						autoMultiLine
						allowClear
						clearable
						maxItem={500}
						zIndex={1200}
						placeholder="多个款式编码，以逗号隔开"
						message="多个款式编码， 每行输入1个内容，最多500个"
					/>
				</Form.Item>
			</div>

			<div className={styles.AntdWrapper}>
				<Form.Item label="" name="goodsAbbreviation" colon={false}>
					<Input allowClear placeholder="商品简称" />
				</Form.Item>
			</div>

			<AntdWrapper style={{ width: 210 }}>
				<Form.Item
					colon={false}
					label={
						<Select
							onChange={e => {
								console.log("minPriceMap[priceType]", minPriceMap[priceType]);
								form.setFieldsValue(minPriceMap[priceType], undefined);
								form.setFieldsValue(maxPriceMap[priceType], undefined);
								handleSetQuery({
									[minPriceMap[priceType]]: undefined,
									[maxPriceMap[priceType]]: undefined
								});
								setPriceType(e);
							}}
							value={priceType}
							bordered={false}
						>
							<Option value={1}>成本价</Option>
							<Option value={2}>零售价</Option>
							<Option value={3}>市场价</Option>
						</Select>
					}
				>
					<Form.Item
						style={{
							display: "inline-block",
							width: "40%"
							//   width: '80px',
							// marginRight: 10
						}}
						name={minPriceMap[priceType]}
					>
						<InputNumber bordered={false} precision="2" min={0} max={9999999.99} placeholder="最小值" />
					</Form.Item>
					<span
						style={{
							display: "inline-block",
							textAlign: "center"
							// margin: "0 9px"
						}}
					>
						<SwapRightOutlined />
					</span>
					<Form.Item style={{ display: "inline-block", width: "40%" }} name={maxPriceMap[priceType]}>
						<InputNumber bordered={false} precision="2" min={0} max={9999999.99} placeholder="最大值" />
					</Form.Item>
				</Form.Item>
			</AntdWrapper>

			<AntdWrapper
				label={<span style={{ fontSize: "12px", color: "#727E8F", marginLeft: "2px" }}>重量范围</span>}
				style={{ width: 434 }}
			>
				<Form.Item colon={false}>
					<Form.Item
						style={{
							display: "inline-block",
							width: "40%"
							//   width: '80px',
							// marginRight: 10
						}}
						name="weightMin"
					>
						<InputNumber bordered={false} precision="2" min={0} max={9999999.99} placeholder="最小值" />
					</Form.Item>
					kg
					<span
						style={{
							display: "inline-block",
							textAlign: "center"
							// margin: "0 9px"
						}}
					>
						<SwapRightOutlined />
					</span>
					<Form.Item style={{ display: "inline-block", width: "40%" }} name="weightMax">
						<InputNumber bordered={false} precision="2" min={0} max={9999999.99} placeholder="最大值" />
					</Form.Item>
					kg
				</Form.Item>
			</AntdWrapper>

			{/* <Form.Item label=" " colon={false}> */}
			<div style={{ display: "flex", marginBottom: "16px" }}>
				<div style={{ marginRight: "16px", display: "flex" }}>
					{items.length > 0 ? items.map(item => <QueryButton item={item} {...queryButtonProps} />) : ""}
				</div>
				<Button onClick={handleSaveQuickSearch} style={{ marginRight: "8px", height: "32px", fontSize: "12px" }}>
					另存为快捷查询
				</Button>
				<Button
					type="primary"
					htmlType="submit"
					style={{ marginRight: "8px", height: "32px", fontSize: "12px" }}
					icon={<SearchOutlined />}
				>
					查询
				</Button>
				<Button
					style={{ marginLeft: "8px", fontSize: "12px" }}
					size="middle"
					onClick={onReset}
					icon={<IconFont type="iconformReset" />}
				>
					重置
				</Button>
			</div>
			{/* </Form.Item> */}
		</Form>
	);
};

export default SearchForm;
